<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wh:pd:whPdStockPosBill:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #whPdStockPosBillsList>
        <BasicTable
          @register="registerWhPdStockPosBillsTable"
          @row-click="handleWhPdStockPosBillsRowClick"
        />
        <a-button class="mt-2" @click="handleWhPdStockPosBillsAdd" v-auth="'wh:pd:whPdStockPosBill:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWhPdWhPdStockPosBillForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WhPdStockPosBill, whPdStockPosBillSave, whPdStockPosBillForm } from '/@/api/wms/wh/pd/whPdStockPosBill';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.pd.whPdStockPosBill');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WhPdStockPosBill>({} as WhPdStockPosBill);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增盘点') : t('编辑盘点'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('盘点方式'),
      field: 'pdType',
      component: 'Input',
      componentProps: {
        maxlength: 1,
      },
      required: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      required: true,
    },
    {
      label: t('盘点状态'),
      field: 'pdStatus',
      component: 'Input',
      componentProps: {
        maxlength: 1,
      },
    },
    {
      label: t('总数'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ required: true }, { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('实盘总数'),
      field: 'sumqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('仓库'),
      field: 'whcode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('货位'),
      field: 'posCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('公司编码'),
      field: 'companyCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
    },
    {
      label: t('公司名称'),
      field: 'companyname',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('盘点单明细 - 仓库/货位'),
      field: 'whPdStockPosBillsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'whPdStockPosBillsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerWhPdStockPosBillsTable, whPdStockPosBillsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleWhPdStockPosBillsDelete.bind(this, record),
          },
          auth: 'wh:pd:whPdStockPosBill:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWhPdStockPosBillsTableData(_res: Recordable) {
    whPdStockPosBillsTable.setColumns([
      {
        title: t('货位'),
        dataIndex: 'posCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
      },
      {
        title: t('账存数'),
        dataIndex: 'iqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      {
        title: t('实盘数'),
        dataIndex: 'frealqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('来源id'),
        dataIndex: 'sourceId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('来源单号'),
        dataIndex: 'sourceNo',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('来源明细ID'),
        dataIndex: 'sourceDid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('行备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
    ]);
    whPdStockPosBillsTable.setTableData(record.value.whPdStockPosBillsList || []);
  }

  function handleWhPdStockPosBillsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWhPdStockPosBillsAdd() {
    whPdStockPosBillsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWhPdStockPosBillsDelete(record: Recordable) {
    whPdStockPosBillsTable.deleteTableDataRecord(record);
  }

  async function getWhPdStockPosBillsList() {
    let whPdStockPosBillsListValid = true;
    let whPdStockPosBillsList: Recordable[] = [];
    for (const record of whPdStockPosBillsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whPdStockPosBillsListValid = false;
      }
      whPdStockPosBillsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of whPdStockPosBillsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whPdStockPosBillsList.push({
        ...record,
        status: '1',
      });
    }
    if (!whPdStockPosBillsListValid) {
      throw { errorFields: [{ name: ['whPdStockPosBillsList'] }] };
    }
    return whPdStockPosBillsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await whPdStockPosBillForm(data);
    record.value = (res.whPdStockPosBill || {}) as WhPdStockPosBill;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setWhPdStockPosBillsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.whPdStockPosBillsList = await getWhPdStockPosBillsList();
      // console.log('submit', params, data, record);
      const res = await whPdStockPosBillSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
